# -*- coding:utf-8 -*-
"""
@Time : 2021/1/18 00:03
@Author: langengel
@Des: 公共模块
"""
from models.saas import User, Service


async def delete_service(s_id: str):
    """
    删除服务商
    :param s_id: 服务商业务ID
    :return: boolean
    """
    service_del = await Service().filter(s_id=s_id).delete()
    if service_del:
        return True

    return False


def get_tree(data, pid):
    """
    地区层级遍历
    :param data: 地区数据
    :param pid: 父ID
    :return: list
    """
    result = []
    for item in data:
        if pid == item["pid"]:
            temp = get_tree(data, item["region_Id"])
            if len(temp) > 0:
                item["children"] = temp
            result.append(item)
    return result


async def check_user_for_service(s_id: str, u_id: str):
    """
    用户合法检测
    :param s_id: 服务商id
    :param u_id: 用户id
    :return: False or user
    """

    user_for_service = await User().get_or_none(u_id=u_id).prefetch_related("service")
    await user_for_service.service

    if user_for_service.service.s_id == s_id:
        return user_for_service
    return False


def rule_tree(data, pid):
    """
    权限层级遍历
    :param data: rule[]
    :param pid: 父ID
    :return: list
    """
    result = []
    for item in data:
        if pid == item["pId"]:
            temp = rule_tree(data, item["id"])
            if len(temp) > 0:
                item["children"] = temp
            result.append(item)
    return result
